﻿using Marbles.Data;
using System;
using System.Data;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using Marbles.Core.Helpers;
using Marbles.Core.Web.MVC.Views;

namespace Marbles.Core.Web.State
{
    public class SqlStatePersistanceManager : IStatePersistanceManager
    {

        private string _Connection = string.Empty;
        private CompressionMethod  _CompressionMethod = CompressionMethod.None;

        public SqlStatePersistanceManager(string Connection )
        {
            this._Connection = Connection;
            this._CompressionMethod = CompressionMethod.None;
        }

        public SqlStatePersistanceManager(string Connection, CompressionMethod CompressionMethod)
        {
            this._CompressionMethod = CompressionMethod;
            this._Connection = Connection;
        }

        public string SavePageStateToPersistenceMedium(object state, ViewBase Page)
        {
            StringWriter sw = new StringWriter();
            LosFormatter ser = new LosFormatter();
            ser.Serialize(sw, state);
            sw.Flush();             
            DataSource dbc = new DataSource(_Connection);
            DataSourceCommand cmd = new DataSourceCommand("DELETE FROM ViewState WHERE id = @id;INSERT INTO ViewState(id, viewstate, creationdate) VALUES (@id,@viewstate,@creationdate)");
            cmd.Parameters.Add("@id", Page.ViewStateKey);

            if (this._CompressionMethod == CompressionMethod.None)
            {
                cmd.Parameters.Add("@viewstate", sw.ToString());
            }
            else
            {
                cmd.Parameters.Add("@viewstate", Compression.Compress(sw.ToString(), this._CompressionMethod));
            }
            
            cmd.Parameters.Add("@creationdate", DateTime.Now);
            dbc.ExecuteCommand(cmd);
            return Page.ViewStateUserKey;
        }

        public object LoadPageStateFromPersistenceMedium(ViewBase Page)
        {
            DataSource dbc = new DataSource(_Connection);
            DataSourceCommand cmd = new DataSourceCommand("SELECT viewstate FROM ViewState WHERE id = @id");
            cmd.Parameters.Add("@id", Page.ViewStateKey);
            DataTable dt = dbc.FetchDataTable(cmd);

            if (dt.Rows.Count > 0)
            {
                LosFormatter ser = new LosFormatter();
                string value = dt.Rows[0]["viewstate"].ToString();

                if (this._CompressionMethod != CompressionMethod.None)
                {
                    value = Compression.Decompress(value, this._CompressionMethod);
                }
          
                return ser.Deserialize(value);
            }

            return null;
        }

    }
}
